package com.my.study.redis;
import com.my.util.FileUtils;
import redis.clients.jedis.Jedis;
//import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * Redis分布式锁
 */
public class RedisLock implements Lock {

    private static final String host = "127.0.0.1";
    private static final int port = 6379;

    private static final String KEY = "redisLock_hahah";

   /* @Resource
    private JedisConnectionFactory factory;
*/

    private ThreadLocal<String> threadLocal = new ThreadLocal<>();

    @Override
    public void lock() {
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        String uuid = UUID.randomUUID().toString();
        //Node node = new Node(host, port,0, null, 0);
        //Jedis jedis = (Jedis) factory.getConnection(node).getNativeConnection();
        Jedis jedis = new Jedis(host, port);
        //String res = jedis.set(KEY, "I am locked", "NX", "EX", 2);
        String res = jedis.setex(KEY, 2,"I am locked");

        if("OK".equals(res)){

            System.out.println("lock successfully");
            threadLocal.set("I am locked");
            return true;
        }

        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        String luaScript = FileUtils.loadLuaScript("unlock.lua");
        System.out.println("luaScript is: =====" + luaScript);
        /*Node node = new Node(host, port,0, null, 0);
        Jedis jedis = (Jedis) factory.getConnection(node).getNativeConnection();*/
        Jedis jedis = new Jedis(host, port);
        jedis.eval(luaScript, Arrays.asList(KEY),Arrays.asList(threadLocal.get()));

    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
